<template>
  <div class="app-container goTop .page-component__scroll">
     <div class="headbtn_box">
         <div class="addbutton">
             <el-button type="primary"  size="small" @click="handlerSubmit"  > 保存</el-button>
              <el-button type="danger"  size="small"  @click="clearForm"  > 清空</el-button>
             <el-button type="danger"  size="small"  @click="handlerBack"  > 返回</el-button>
         </div>
     </div>
     <!-- 表单 -->
     <el-form ref="formRef" :model="state.form"     label-width="100px" label-position="left" size="small">
       <div class="mt15" >
         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">试题基本信息</div>
              <!-- 编辑 -->
             <div class="edits"  >
               <el-row :gutter="15">


                  <el-col :span="8">
                     <el-form-item label="所属专业" prop="subjectId"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                       <el-cascader
                         ref="cascaderCourseRef"
v-model="cascaderCourse" :options="courseOptions" :props=" { value:'id',label:'name'}"
                       @change="courseHandleChange" />
                    </el-form-item>
                  </el-col>

                 <el-col :span="8">
                    <el-form-item label="试题类型" prop="questionType" >
                     <el-select v-model="state.form.questionType" placeholder="请选择" @change="questionTypeChange" >
                       <el-option
                           v-for="dict in question_type"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"
                       />
                     </el-select>
                   </el-form-item>
                 </el-col>


                 <el-col :span="8">
                   <el-form-item label="试题难度" prop="difficult" >
                     <el-select v-model="state.form.difficult" placeholder="请选择"  >
                       <el-option
                           v-for="dict in question_difficulty"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"
                       />
                     </el-select>
                   </el-form-item>
                 </el-col>

                <el-col :span="8">
                     <el-form-item label="会员等级" prop="vipLevel">
                         <el-select
                             v-model="state.form.vipLevel"
                             placeholder="会员等级">
                             <el-option
                                 v-for="vip in vipLevelList"
                                 :key="vip.id"
                                 :label="vip.name"
                                 :value="vip.id"
                             />
                         </el-select>
                     </el-form-item>
                </el-col>


                 <el-col :span="8">
                   <el-form-item label="分数" prop="score"  >
                      <el-input  v-model.number="state.form.score"   style="width:60%"></el-input>

                       <el-tooltip class="item" effect="dark" content="分数为0,系统不会计算分数" placement="right">
                            <i class="el-icon-info" style="font-size: 20px;color: red;"></i>
                       </el-tooltip>

                   </el-form-item>
                 </el-col>


                 <el-col :span="8">
                   <el-form-item label="状态" >
                     <el-radio-group v-model="state.form.status">
                           <el-radio
                            v-for="dict in sys_normal_disable"
                         :key="dict.value"
                         :value="dict.value"
                       >{{dict.label}}</el-radio>
                     </el-radio-group>
                   </el-form-item>
                 </el-col>

               </el-row>
             </div>
         </el-card>
       </div>

       <!-- 试题内容 -->
       <div class="mt15" >
         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">试题内容</div>
             <QuillEditor ref="subjectRef" v-model:modelValue="state.form.subject" :minHeight="150"/>
         </el-card>
       </div>

       <!-- 单选题的选项 -->
       <div v-if="state.form.questionType==='1'" class="mt15" >
         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">单选题</div>
             <fieldset id="divObjective" class="appendbox">
                 <table cellspacing="0" cellpadding="0" style="border:1px solid #f2f4f8;" class="common-table table-noborder text-center">
                     <thead>
                         <tr>
                           <th width="8%"  >勾选设置答案</th>
                           <th width="70%">选项内容</th>
                         </tr>
                     </thead>
                     <tbody>
                         <tr v-for="(item,index) in state.form.choose" :key="'sub_'+index">
                          <td>
                               <el-radio  v-model="state.form.correct" :label="String.fromCharCode(65+index)"></el-radio>
                           </td>
                           <td class="textearea">
                               <QuillEditor v-model:modelValue="item.content"  :minHeight="150"/>
                            </td>
                         </tr>

                      <tr   class="operation">
                             <td colspan="3" style="padding-left:38px;padding-bottom:15px;">
                                 <button
type="button"
                                      class="el-button el-button--primary" @click="addOption">
                                      <i class="fa fa-plus" aria-hidden="true"></i>添加选项
                                   </button>
                                 <button
type="button"
                                      class="el-button el-button--danger"  @click="removeOption">
                                    <i class="fa fa-minus" aria-hidden="true"></i>   删减选项
                                 </button>
                             </td>
                         </tr>
                     </tbody>
                 </table>
             </fieldset>

         </el-card>
       </div>

      <!-- 多选题的选项-->
       <div v-if="state.form.questionType==='2'"  class="mt15" >
         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">多选题</div>

             <fieldset id="divObjective" class="appendbox">
                <el-checkbox-group v-model="state.form.correctMutil">
                 <table cellspacing="0" cellpadding="0" style="border:1px solid #f2f4f8;" class="common-table table-noborder text-center">
                     <thead>
                         <tr>
                           <th width="8%"  >勾选设置答案</th>
                           <th width="70%">选项内容</th>
                         </tr>
                     </thead>
                     <tbody>
                         <tr v-for="(item,index) in state.form.choose" :key="'sub_'+index">
                          <td>
                               <el-checkbox   :label="String.fromCharCode(65+index)"></el-checkbox>
                           </td>

                           <td class="textearea">
                               <QuillEditor v-model:modelValue="item.content"  :minHeight="150"/>
                            </td>
                         </tr>


                        <tr   class="operation">
                             <td colspan="3" style="padding-left:38px;padding-bottom:15px;">
                                 <button
type="button"
                                      class="el-button el-button--primary" @click="addOption">
                                      <i class="fa fa-plus" aria-hidden="true"></i>添加选项
                                   </button>
                                 <button
type="button"
                                      class="el-button el-button--danger"  @click="removeOption">
                                    <i class="fa fa-minus" aria-hidden="true"></i>   删减选项
                                 </button>
                             </td>
                         </tr>
                     </tbody>
                 </table>
                 </el-checkbox-group>
             </fieldset>

         </el-card>
       </div>


       <!-- 简答的选项 -->
       <div v-if="state.form.questionType==='3'" class="mt15" >

         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">答案</div>
             <QuillEditor   v-model:modelValue="state.form.correct"  :minHeight="150"/>
         </el-card>
       </div>


       <!-- 答案解析 -->
       <div class="mt15" >
         <el-card class="box-card" shadow="never">
             <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">答案解析</div>
             <QuillEditor v-model:modelValue="state.form.analysis"  :minHeight="150"/>
         </el-card>
       </div>


     </el-form>


    <div class="headbtn_box">
        <div class="addbutton">
            <el-button type="primary"  size="small" @click="handlerSubmit"    > 保存</el-button>
            <el-button type="danger"  size="small" @click="handlerBack"  > 返回</el-button>
        </div>
    </div>

    <el-backtop  :bottom="100"></el-backtop>
  </div>
</template>

<script lang="ts" setup>
import { ref,toRefs, reactive,  getCurrentInstance, ComponentInternalInstance,nextTick} from 'vue';
import {allUserLevelApi} from '@/api/app/userlevel';
import {courseTreeApi} from '@/api/app/course/course';
import QuillEditor from '@/components/Editor/index.vue';
import {addApi,editApi,findByIdApi} from '@/api/app/question';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,question_difficulty,question_type } = proxy!.useDict('sys_normal_disable','question_difficulty','question_type');

//得到数据表单form样式对象
const formRef = ref<FormInstance>();
const cascaderCourseRef=ref();
console.log(cascaderCourseRef);

//会员等级
const vipLevelList=ref([]);

//选中的课程级联的数据
const cascaderCourse=ref([]);
//课程列表
const courseOptions = ref(undefined);

const state=reactive({
    form:{
        id:undefined,
        //多选题答案
        correctMutil:[],
        //单选，简答正确答案
        correct:'',
        score: 0,
        subjectId:undefined,
        courseId:undefined,
        //试题内容
        subject: '',
        questionType:'3',
        difficult: '1',
        vipLevel: 1,
        status:'0',
        //试题解析
        analysis:'',
        //选择项 {content:'内容',correct:true/false}
        choose:[]
    }
});

// 可以解构而不会失去响应性
const stateRef =  toRefs(state);

//课程选择后的事件
function courseHandleChange(value){
    if(value.length===3){
        state.form.subjectId = value[0];
        state.form.courseId= value[2];
    }else{
        ElMessage.error('所属专业数据有误，不能选择');
        cascaderCourse.value=[];
        state.form.subjectId = undefined;
        state.form.courseId = undefined;
    }
}

//试题类型变化
function questionTypeChange(val){
    state.form.correct='';
    state.form.correctMutil=[];
    if(val==='3'){
        state.form.choose =[];
    }else{
        state.form.choose =[
            {content:'',correct:false},
            {content:'',correct:false},
            {content:'',correct:false},
            {content:'',correct:false}
        ];
    }
}


//添加选项
function addOption(){
    state.form.choose.push({ content:'',correct:false});
}
//移出最后一个选项
function removeOption(){
    state.form.choose.splice(state.form.choose.length-1,1);
}

function  handlerBack(){
    const obj = { path: '/app/question' };
    proxy!.$tab.closeOpenPage(obj);
}

function  handlerSubmit(){
    formRef.value.validate(valid => {
        if (valid) {
            ElMessageBox.confirm('确定要保存数据吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    executeSubmit();
                });

        }
    });
}

//保存试题
function executeSubmit(){
    //主键有值
    let api;
    if(state.form.id){
        api=editApi;
    }else{
        api=addApi;
    }
    console.log(api);
    //调用方法
    api(state.form).then(resp=> {

        //修改直接关闭当前选项卡
        if(state.form.id){
            ElMessage.success('修改数据成功');
            handlerBack();
        }else{

            ElMessageBox.confirm('保存数据成功，是否继续添加数据?', '提示', {
                confirmButtonText: '继续添加',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    clearForm();

                })
                .catch(() => {
                    //不继续添加,跳转查询界面
                    handlerBack();
                });


        }


    });
}

function clearForm(){
    stateRef.form.value.id=undefined;
    stateRef.form.value.correctMutil=[];
    stateRef.form.value.correct='';
    stateRef.form.value.score=0;
    stateRef.form.value.subjectId=undefined;
    stateRef.form.value.courseId=undefined;
    stateRef.form.value.subject='';
    stateRef.form.value.difficult='1';
    stateRef.form.value.vipLevel=1;
    stateRef.form.value.status='0';
    //试题解析
    stateRef.form.value.analysis='';
    //选择项 {content:'内容',correct:true/false}
    stateRef.form.value.choose=[];
    //简答
    if(stateRef.form.value.questionType==='3'){
        state.form.choose =[];
    }else{
        //单选和多选
        state.form.choose =[
            {content:'',correct:false},
            {content:'',correct:false},
            {content:'',correct:false},
            {content:'',correct:false}
        ];
    }

}
//初始会员等级
function initUserLevel(){
    allUserLevelApi().then(resp=>{
        vipLevelList.value= resp.data;
    });
}

//加载树型节点
function initCourseTree(){
    courseTreeApi().then(resp=>{
        console.log(resp);
        courseOptions.value=resp.data;
    });
}

initCourseTree();

initUserLevel();

//判断是否是修改数据
console.log(route);
if(route.params && route.params.id){
    console.log(route.params);
    findByIdApi(route.params.id).then(resp=>{
        console.log(resp);
        stateRef.form.value=resp.data;
        cascaderCourse.value=resp.data.cascaderCourse;
    });
}

</script>

<style  lang="scss" >
   @import url("../../../assets/styles/question.scss");
</style>
